package com.ynny.UserManage.dao;

import com.ynny.UserManage.enity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImp  implements UserDao{
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Override
    public int addUser( String password, String username, Integer id) {
        String sql = "insert into user(username,password,id) values(?,?,?)";
        return jdbcTemplate.update(sql,username,password,id);
    }
    //查询
    @Override
    public User queryUserById(Integer id) {
        String sql = "select * from user where id = ?";
        return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),id);
    }
    @Override
    public int updateUser(Integer id, String password) {
        String sql = "update user set password = ?  where id = ?";
        return jdbcTemplate.update(sql,password,id);
    }
    @Override
    public int deleteUser(Integer id) {
        String sql = "delete from user where id = ?";
        return jdbcTemplate.update(sql,id);
    }
    @Override
    public List<User> queryAllUser() {
        String sql = "select * from user";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class));
    }
    @Override
    public User queryUserByName(String username) {
        String sql = "select * from user where username = ?";
        List<User> user = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class),username);
        return user.isEmpty() ? null : user.get(0);
    }
}
